package com.max.sportmanage.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: java-sport-manage
 * @description: redis工具类
 * @author: max-qaq
 * @create: 2021-11-08 23:11
 **/
@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * redis传值
     * @param key
     * @param value
     * @return
     */
    public boolean setValue(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            log.error("向redis存值异常--->{}",e.getMessage());
            return false;
        }
    }

    /**
     * 设置过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setValueTime(String key,Object value,long time){
        try {
            if (time > 0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.MINUTES);
            } else{
                redisTemplate.opsForValue().set(key,value);
            }
            return true;
        }catch (Exception e){
            log.error("设置redis过期时间异常---->{}",e.getMessage());
            return false;
        }
    }

    /**
     * 获取value的值
     * @param key
     * @return
     */
    public Object getValue(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除key,可以是数组
     * @param keys
     * @return
     */
    public void delKey(String... keys){
        if(null != keys && keys.length > 0){
            if (keys.length == 1){
                redisTemplate.delete(keys[0]);
            }else{
                for(String key : keys){
                    redisTemplate.delete(key);
                }
            }
        }
    }

    /**
     * 判断是否含有key
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            log.error("redis值不存在异常--->{}",e.getMessage());
            return false;
        }
    }

    /**
     * 判断是否过期
     * 0 ->永久有效
     * 否则返回多久过期
     * @param key
     * @return
     */
    public Long isExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.MINUTES);
    }

    public boolean expire(String key,long time){
        try {
            if(time > 0){
                redisTemplate.expire(key,time,TimeUnit.SECONDS);
                return true;
            }
            return false;
        }catch (Exception e){
            log.error("设置过期时间异常--->{}",e.getMessage());
            return false;
        }
    }
}
